package com.zyh.dao;
import com.zyh.entity.Tag;
import com.zyh.utils.TransactionManager;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class TagDao {

    public Tag selectById(Integer tagId) throws SQLException {
        String sql = "SELECT tag_id, name FROM tags WHERE tag_id=?";
        Connection conn = TransactionManager.getCurrentConnection();
        try (PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setInt(1, tagId);
            ResultSet rs = ps.executeQuery();
            if (rs.next()) {
                return new Tag(rs.getInt("tag_id"), rs.getString("name"));
            }
            return null;
        }
    }

    public void add(Tag tag) throws SQLException {
        String sql = "INSERT INTO tags(name) VALUES(?)";
        Connection conn = TransactionManager.getCurrentConnection();
        try (PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setString(1, tag.getName());
            ps.executeUpdate();
        }
    }

    public void deleteById(Integer tagId) throws SQLException {
        String sql = "DELETE FROM tags WHERE tag_id=?";
        Connection conn = TransactionManager.getCurrentConnection();
        try (PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setInt(1, tagId);
            ps.executeUpdate();
        }
    }

    public List<Tag> selectAll() throws SQLException {
        List<Tag> tags = new ArrayList<>();
        String sql = "SELECT tag_id, name FROM tags ORDER BY tag_id";
        Connection conn = TransactionManager.getCurrentConnection();
        try (PreparedStatement ps = conn.prepareStatement(sql);
             ResultSet rs = ps.executeQuery()) {
            while (rs.next()) {
                tags.add(new Tag(
                        rs.getInt("tag_id"),
                        rs.getString("name")
                ));
            }
        }
        return tags;
    }

    public void updateById(Integer tagId, String newName) throws SQLException {
        String sql = "UPDATE tags SET name=? WHERE tag_id=?";
        Connection conn = TransactionManager.getCurrentConnection();
        try (PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setString(1, newName);
            ps.setInt(2, tagId);
            ps.executeUpdate();
        }
    }
}
